package com.rajaev.dtu.tractor.infrastructure.helper;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;
import com.rajaev.dtu.tractor.infrastructure.config.MongoDbConfig;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class MongoDbUtils {

    @Autowired
    private MongoDbConfig mongoDbConfig;

    private MongoClient mongoClient;

    @PostConstruct
    void init() {
        if (StringUtils.isNotEmpty(mongoDbConfig.getAuth())) {
            ServerAddress serverAddress = new ServerAddress(mongoDbConfig.getIp(), mongoDbConfig.getPort());
            MongoCredential credential = MongoCredential.createCredential(mongoDbConfig.getUserName(), mongoDbConfig.getDataBase(), mongoDbConfig.getAuth().toCharArray());
            mongoClient = new MongoClient(serverAddress, credential, MongoClientOptions.builder().build());
        } else {
            mongoClient = new MongoClient(mongoDbConfig.getIp(), mongoDbConfig.getPort());
        }
    }


    /**
     * 获取mongodb的数据库
     *
     * @return
     */
    public MongoDatabase getDatabase() {
        return mongoClient.getDatabase(mongoDbConfig.getDataBase());
    }


    public MongoClient getMongoClient() {
        return mongoClient;
    }

    public void setMongoClient(MongoClient mongoClient) {
        this.mongoClient = mongoClient;
    }

    public static void main(String[] args) {
        MongoDbConfig mongoDbConfig = new MongoDbConfig();
        MongoClient mongoClient;
        mongoDbConfig.setDataBase("dtuTractor");
        mongoDbConfig.setIp("106.15.124.200");
        mongoDbConfig.setPort(10127);
        if (StringUtils.isNotEmpty(mongoDbConfig.getAuth())) {
            ServerAddress serverAddress = new ServerAddress(mongoDbConfig.getIp(), mongoDbConfig.getPort());
            MongoCredential credential = MongoCredential.createCredential(mongoDbConfig.getUserName(), mongoDbConfig.getDataBase(), mongoDbConfig.getAuth().toCharArray());
            mongoClient = new MongoClient(serverAddress, credential, MongoClientOptions.builder().build());
        } else {
            mongoClient = new MongoClient(mongoDbConfig.getIp(), mongoDbConfig.getPort());
        }
        Document document = new Document();
        document.put("vin","2121212");
        document.put("createAt",124555);
        mongoClient.getDatabase("dtuTractor").getCollection("electricityMessage").insertOne(document);
    }
}
